import axios from 'axios'

export interface CasdoorConfig {
  endpoint: string
  clientId: string
  clientSecret: string
  organizationName: string
  applicationName: string
}

export const casdoorConfig: CasdoorConfig = {
  endpoint: process.env.CASDOOR_ENDPOINT || 'http://192.168.41.62:8000',
  clientId: process.env.CASDOOR_CLIENT_ID || '',
  clientSecret: process.env.CASDOOR_CLIENT_SECRET || '',
  organizationName: process.env.CASDOOR_ORGANIZATION_NAME || 'Agi-Todo',
  applicationName: process.env.CASDOOR_APPLICATION_NAME || 'Agi-Todo'
}

export interface CasdoorUser {
  id: string
  name: string
  displayName: string
  email: string
  avatar: string
  phone: string
  address: string[]
  affiliation: string
  tag: string
  language: string
  score: number
  ranking: number
  isOnline: boolean
  isAdmin: boolean
  isGlobalAdmin: boolean
  isForbidden: boolean
  isDeleted: boolean
  signupApplication: string
  hash: string
  preHash: string
  createdTime: string
  updatedTime: string
}

// 生成Casdoor登录URL
export function getCasdoorLoginUrl(redirectUri: string, state?: string): string {
  const params = new URLSearchParams({
    client_id: casdoorConfig.clientId,
    response_type: 'code',
    redirect_uri: redirectUri,
    scope: 'openid profile email',
    state: state || ''
  })

  return `${casdoorConfig.endpoint}/login/oauth/authorize?${params.toString()}`
}

// 生成Casdoor注册URL - 方法1：使用OAuth授权端点
export function getCasdoorRegisterUrl(redirectUri: string, state?: string): string {
  const params = new URLSearchParams({
    client_id: casdoorConfig.clientId,
    response_type: 'code',
    redirect_uri: redirectUri,
    scope: 'openid profile email',
    state: state || ''
  })

  // 直接使用登录授权端点，用户可以在登录页面选择注册
  return `${casdoorConfig.endpoint}/login/oauth/authorize?${params.toString()}`
}

// 备用注册URL - 方法2：直接跳转到组织的注册页面
export function getCasdoorSignupPageUrl(): string {
  return `${casdoorConfig.endpoint}/signup/${casdoorConfig.organizationName}`
}

// 备用注册URL - 方法3：跳转到应用的注册页面
export function getCasdoorAppSignupUrl(): string {
  return `${casdoorConfig.endpoint}/signup/${casdoorConfig.organizationName}/${casdoorConfig.applicationName}`
}

// 使用授权码获取访问令牌
export async function getAccessToken(code: string, redirectUri: string): Promise<string> {
  try {
    console.log('请求访问令牌...')
    console.log('Code:', code)
    console.log('Redirect URI:', redirectUri)
    console.log('Client ID:', casdoorConfig.clientId)
    console.log('Endpoint:', casdoorConfig.endpoint)

    const response = await axios.post(`${casdoorConfig.endpoint}/api/login/oauth/access_token`, {
      grant_type: 'authorization_code',
      client_id: casdoorConfig.clientId,
      client_secret: casdoorConfig.clientSecret,
      code: code,
      redirect_uri: redirectUri
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    console.log('访问令牌响应状态:', response.status)
    console.log('访问令牌响应数据:', response.data)

    if (!response.data.access_token) {
      throw new Error('响应中没有访问令牌')
    }

    return response.data.access_token
  } catch (error) {
    console.error('获取访问令牌失败:', error)
    if (axios.isAxiosError(error)) {
      console.error('响应状态:', error.response?.status)
      console.error('响应数据:', error.response?.data)
      console.error('请求配置:', error.config)
    }
    throw new Error('获取访问令牌失败')
  }
}

// 使用访问令牌获取用户信息
export async function getCasdoorUser(accessToken: string): Promise<CasdoorUser> {
  try {
    console.log('请求用户信息...')
    console.log('Access Token:', accessToken ? '存在' : '不存在')

    const response = await axios.get(`${casdoorConfig.endpoint}/api/get-account`, {
      headers: {
        Authorization: `Bearer ${accessToken}`
      }
    })

    console.log('用户信息响应状态:', response.status)
    // console.log('用户信息响应数据:', response.data)

    if (!response.data.data) {
      throw new Error('响应中没有用户数据')
    }

    return response.data.data
  } catch (error) {
    console.error('获取用户信息失败:', error)
    if (axios.isAxiosError(error)) {
      console.error('响应状态:', error.response?.status)
      console.error('响应数据:', error.response?.data)
    }
    throw new Error('获取用户信息失败')
  }
}

// 验证访问令牌
export async function verifyAccessToken(accessToken: string): Promise<{ valid: boolean; error?: string }> {
  try {
    await getCasdoorUser(accessToken)
    return { valid: true }
  } catch (error) {
    console.error('验证访问令牌失败:', error)
    
    if (axios.isAxiosError(error)) {
      if (error.code === 'ETIMEDOUT' || error.code === 'ECONNREFUSED') {
        return { 
          valid: false, 
          error: 'Casdoor服务连接超时，请检查网络连接或联系管理员' 
        }
      } else if (error.response?.status === 401) {
        return { 
          valid: false, 
          error: '访问令牌已过期，请重新登录' 
        }
      } else if (error.response?.status && error.response.status >= 500) {
        return { 
          valid: false, 
          error: 'Casdoor服务暂时不可用，请稍后重试' 
        }
      }
    }
    
    return { 
      valid: false, 
      error: '验证访问令牌失败，请重新登录' 
    }
  }
} 